import Vue from "vue";
import axios, { Method } from "axios";
import { netConfig } from "@/config";
import { getAccessToken } from "@/utils/accessToken";
import store from "@/store";
import { isArray } from "@/utils/validate";

export class request {
  /**
   *
   * @description 处理code异常
   * @param {*} code
   * @param {*} msg
   */
  handleCode(code: number, msg: string) {}
  /**
   * 获取设置
   * @returns
   */
  protected createRequest() {
    const reqConfig = {
      baseURL: netConfig.baseURL,
      timeout: netConfig.requestTimeout,
      method: "POST" as Method,
      headers: {
        contentType: netConfig.contentType,
        Authorization: getAccessToken(),
      },
    };
    return axios.create(reqConfig);
  }
  get(url: string) {
    return this.ajax(
      url,
      {},
      {
        method: "GET" as Method,
      }
    );
  }
  post(url: string, data: any) {
    return this.ajax(url, data, {
      method: "POST" as Method,
    });
  }
  async ajax(url: string, data?: any, config?: any) {
    const req = this.createRequest();
    if (!config) {
      config = {};
    }
    config.url = url;
    const rps = await req.request(config);
    const ret = rps.data || {};
    this.handleCode(rps.status, "");
    return ret;
  }
}
